<template>
  <div class="roles">
    <el-breadcrumb separator-class="el-icon-arrow-right">
      <el-breadcrumb-item :to="{ path: '/welcome' }">首页</el-breadcrumb-item>
      <el-breadcrumb-item>权限管理</el-breadcrumb-item>
      <el-breadcrumb-item>角色列表</el-breadcrumb-item>
    </el-breadcrumb>

    <el-card class="box-card">
      <el-button type="primary" @click="add" class="car_button"
        >添加角色</el-button
      >

      <el-table :data="tableData" stripe border style="width: 100%">
        <el-table-column type="expand">
          <template slot-scope="scope">
            <div v-if="scope.row.children.length!=0">
              <el-row
                v-for="(item, index) in scope.row.children"
                :key="item.id"
                :class="index == 0 ? '' : 'border'"
              >
                <el-col :span="6" class="vconent">
                  <!-- 第一行 -->
                  <el-tag
                    closable
                    type="success"
                    @close="remove(scope.row, item.id)"
                  >
                    {{ item.authName }}
                  </el-tag>
                </el-col>
                <el-col :span="18">
                  <el-row
                    v-for="(item2, index2) in item.children"
                    :key="item2.id"
                    :class="index2 == 0 ? '' : 'border'"
                  >
                    <el-col :span="4">
                      <!-- 第二行 -->
                      <el-tag
                        closable
                        type="warning"
                        @close="remove(scope.row, item2.id)"
                      >
                        {{ item2.authName }}
                      </el-tag>
                    </el-col>
                    <el-col :span="20">
                      <!-- 第三行 -->
                      <el-tag
                        closable
                        type="danger"
                        @close="remove(scope.row, item3.id)"
                        v-for="(item3, index3) in item2.children"
                        :key="item3.id"
                      >
                        {{ item3.authName }}
                      </el-tag>
                    </el-col>
                  </el-row>
                </el-col>
              </el-row>
            </div>
            <div v-else>暂无权限</div>
          </template>
        </el-table-column>

        <el-table-column type="index" width="50" label="#"> </el-table-column>
        <el-table-column prop="roleName" label="角色名称"> </el-table-column>
        <el-table-column prop="roleDesc" label="角色描述"> </el-table-column>
        <el-table-column label="操作">
          <template slot-scope="scope">
            <el-button
              type="primary"
              size="mini"
              icon="el-icon-edit"
              @click="handleEdit(scope.row)"
              >编辑</el-button
            >
            <el-button
              type="danger"
              size="mini"
              icon="el-icon-delete"
              @click="handleDelete(scope.row)"
              >删除</el-button
            >
            <el-button
              type="warning"
              size="mini"
              icon="el-icon-setting"
              @click="rightsModel(scope.row)"
              >分配权限</el-button
            >
          </template>
        </el-table-column>
      </el-table>
    </el-card>

    <!-- 添加模态框 -->
    <el-dialog
      :title="editId ? '编辑用户' : '添加用户'"
      :visible.sync="dialogFormVisible"
    >
      <el-form
        :model="ruleForm"
        :rules="rules"
        ref="ruleForm"
        label-width="100px"
        class="demo-ruleForm"
      >
        <el-form-item label="角色名称" prop="roleName">
          <el-input v-model="ruleForm.roleName"></el-input>
        </el-form-item>
        <el-form-item label="角色描述" prop="roleDesc">
          <el-input v-model="ruleForm.roleDesc"></el-input>
        </el-form-item>
      </el-form>
      <div slot="footer" class="dialog-footer">
        <el-button @click="resetForm('ruleForm')">取 消</el-button>
        <el-button type="primary" @click="submitForm('ruleForm')"
          >确 定</el-button
        >
      </div>
    </el-dialog>

    <!-- 分配权限 -->
    <el-dialog title="分配权限" :visible.sync="dialogVisible" width="60%">
      <el-tree
        :data="treelist"
        show-checkbox
        node-key="id"
        default-expand-all
        :props="defaultProps"
        :default-checked-keys="checkList"
        ref="tree"
      >
      </el-tree>
      <span slot="footer" class="dialog-footer">
        <el-button @click="dialogVisible = false">取 消</el-button>
        <el-button type="primary" @click="getYeas">确 定</el-button>
      </span>
    </el-dialog>
  </div>
</template>
<script>
import {
  pleaRoles,
  pleaRole,
  pleaEditid,
  pleaDel,
  pleaTree,
  Addroles,
  pleaRemove,
} from "../utils/http";
export default {
  data() {
    return {
      tableData: [],
      dialogFormVisible: false,
      ruleForm: {
        roleName: "",
        roleDesc: "",
      },
      rules: {
        roleName: [
          { required: true, message: "请输入用户名", trigger: "blur" },
        ],
        roleDesc: [
          { required: true, message: "请输入角色描述", trigger: "blur" },
        ],
      },
      editId: "", //修改id
      dialogVisible: false, //分配权限
      treelist: [], //接收树濑图数据
      defaultProps: {
        children: "children",
        label: "authName",
      },
      rolesId: "", //保存分配权限id
      roleslist: [], //保存选中后的权限
      checkList: [], //回填树状图
    };
  },
  created() {
    this.getUsers();
  },
  methods: {
    getUsers() {
      pleaRoles().then((res) => {
        // console.log(res);
        if (res.meta.status == 200) {
          this.tableData = res.data;
        }
      });
      pleaTree().then((res) => {
        // console.log(res);
        this.treelist = res.data;
      });
    },
    //添加
    add() {
      this.dialogFormVisible = true;
      this.ruleForm = {};
      this.editId = "";
    },
    //确定添加
    submitForm(formName) {
      this.$refs[formName].validate((valid) => {
        if (valid) {
          // alert("submit!");
          if (this.editId) {
            //编辑
            pleaEditid(this.ruleForm).then((res) => {
              // console.log(res);
              if (res.meta.status == 200) {
                this.getUsers();
                this.$message({
                  type: "success",
                  message: res.meta.msg,
                });
                this.dialogFormVisible = false;
                this.ruleForm = {};
                this.editId = "";
              } else {
                this.$message({
                  type: "danger",
                  message: res.meta.msg,
                });
              }
            });
          } else {
            //添加
            pleaRole(this.ruleForm).then((res) => {
              if (res.meta.status == 201) {
                this.getUsers();
                this.$message({
                  type: "success",
                  message: res.meta.msg,
                });
                this.dialogFormVisible = false;
                this.ruleForm = {};
              } else {
                this.$message({
                  type: "danger",
                  message: res.meta.msg,
                });
              }
            });
          }
        } else {
          console.log("error submit!!");
          return false;
        }
      });
    },
    resetForm(formName) {
      this.$refs[formName].resetFields();
      this.dialogFormVisible = false;
    },
    //编辑
    handleEdit(row) {
      // console.log(row);
      this.editId = row.id;
      this.ruleForm = { ...row };
      this.dialogFormVisible = true;
    },
    //删除
    handleDelete(row) {
      this.$confirm("此操作将永久删除该文件, 是否继续?", "提示", {
        confirmButtonText: "确定",
        cancelButtonText: "取消",
        type: "warning",
      })
        .then(() => {
          pleaDel(row).then((res) => {
            // console.log(res);
            this.getUsers();
          });
          this.$message({
            type: "success",
            message: "删除成功!",
          });
        })
        .catch(() => {
          this.$message({
            type: "info",
            message: "已取消删除",
          });
        });
    },
    //分配权限
    rightsModel(row) {
      // if (this.rolesId) {
      //   // this.treelist=this.roleslist
      //   this.rolesId=''
      // } else {

      // }
      this.dialogVisible = true;
      this.rolesId = row.id;
      pleaTree().then((res) => {
        // console.log(res);
        this.treelist = res.data;
        console.log(this.treelist);
      });
      let arr = [];
      function fn(row) {
       row.forEach(item=>{
        if(item.children){
         return fn(item.children)
        }else {
          arr.push(item.id)
        }
       })
      }
      fn(row.children);
      this.checkList = arr;
    },
    //确定分配权限
    getYeas() {
      // console.log(this.$refs.tree.getCheckedNodes());    //返回被选中的数组
      // console.log(this.$refs.tree.getCheckedKeys());    //返回key值
      //首先判断选中的长度不为0
      if (
        this.$refs.tree.getCheckedNodes().length > 0 ||
        this.$refs.tree.getCheckedKeys() > 0
      ) {
        let arr1 = this.$refs.tree.getCheckedKeys();
        let arr2 = this.$refs.tree.getCheckedNodes();
        let arr3 = [...arr1, ...arr2];
        this.roleslist = arr3;
        Addroles({ id: this.rolesId, rids: arr3.join(",") }).then((res) => {
          console.log(res);
          if (res.meta.status == 200) {
            this.getUsers();
            this.dialogVisible = false;
            this.$message({
              type: "success",
              message: res.meta.msg,
            });
          } else {
            this.$message({
              type: "danger",
              message: res.meta.msg,
            });
          }
        });
      }
    },
    //删除角色权限
    remove(row, rightId) {
      console.log(row, rightId);
      this.$confirm("此操作将永久删除该文件, 是否继续?", "提示", {
        confirmButtonText: "确定",
        cancelButtonText: "取消",
        type: "warning",
      })
        .then(() => {
          pleaRemove({ roleId: Number(row.id), rightId: Number(rightId) }).then(
            (res) => {
              console.log(res);
              if (res.meta.status == 200) {
                row.children = res.data;
                // this.getUsers();
                this.$message({
                  type: "success",
                  message: res.meta.msg,
                });
              } else {
                this.$message({
                  type: "danger",
                  message: res.meta.msg,
                });
              }
            }
          );
        })
        .catch(() => {
          this.$message({
            type: "info",
            message: "已取消删除",
          });
        });
    },
  },
};
</script>
<style lang="scss" scoped>
::v-deep .el-breadcrumb {
  margin-bottom: 20px;
}
.car_button {
  margin-bottom: 20px;
}
::v-deep .el-col-6 {
  // line-height: 64px;
  text-align: center;
  padding-top: 5px;
}
.el-row {
  // border: 1px solid #ccc;
  display: flex;
  align-items: center;
  padding: 5px;
  .el-tag {
    margin: 5px;
  }
}
.vconent {
  text-align: center;
}
.border {
  border-top: #ccc 1px solid;
}
</style>